package com.project.controller;

import com.project.pojo.Product;
import com.project.service.ProductService;
import com.project.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /*
    * 乐观锁
    * */
    @PostMapping("/updataProduct")
    public Result updataProduct(@RequestParam int num) {
        boolean update = productService.updateStock(num);
        if (update) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    /*
     * synchronized实现悲观锁
     * */
    @PostMapping("/updataProduct2")
    public Result updataProduct2(@RequestParam int num) {
        boolean update = productService.updateStock2(num);
        if (update) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    /*
     * for update实现悲观锁（数据库行锁）
     * */
    @PostMapping("/updataProduct3")
    public Result updataProduct3(@RequestParam int num) {
        boolean update = productService.updateStock3(num);
        if (update) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    /*
    * 逻辑删除
    * */
    @GetMapping("/deleteProduct")
    public Result deleteProduct(@RequestParam Long id) {
        boolean delete = productService.deleteProduct(id);
        if (delete) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
    @GetMapping("/list")
    public Result list() {
        List<Product> list = productService.list();
        return Result.success(list);
    }
    @GetMapping("/insertRedis")
    public Result insertRedis() {
        boolean insert = productService.insertRedis();
        if (insert) {
            return Result.success("插入成功");
        }
        return Result.error("插入失败");
    }
}
